package se.djupfeldt.oscar.logbook.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import se.djupfeldt.oscar.logbook.Logbook;

public class ServerHandler {
    private static ServerHandler instance;
    private int port;
    private int maxCLients;
    protected boolean running;
    
    private LinkedList<ConnectionHandler> clients;
    
    private ServerHandler() {
	
    }

    public static ServerHandler getInstance() {
	if (instance == null) {
	    instance = new ServerHandler();
	}
	
	return instance;
    }
    
    public boolean init() {
	port = Logbook.properties.getInt("server.port", 4444);
	maxCLients = Logbook.properties.getInt("server.maxClients", 1);
	clients = new LinkedList<ConnectionHandler>();
	return true;
    }
    
    public void start() {
	new Thread("Server") {
	    @Override
	    public void run() {
		try {
		    running = true;
		    ServerSocket serverSocket = new ServerSocket(port);
		    Logger.getLogger(getClass()).info("Logbook server started. Listening on port " + port);
		    while (running) {
			if (clients.size() < maxCLients) {
			    Socket clientSocket = serverSocket.accept();
			    ConnectionHandler connectionHandler = new ConnectionHandler(clientSocket);
			    new Thread(connectionHandler).start();
			    clients.add(connectionHandler);
			    Logger.getLogger(getClass()).info("Client " + clients.size() + "/" + maxCLients +" connected from: " + clientSocket.getInetAddress());
			} else {
			    Thread.sleep(128);
			}
		    }
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		} catch (InterruptedException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    }
	}.start();
    }

    public void removeClient(ConnectionHandler connectionHandler) {
	Logger.getLogger(getClass()).info("Client disconnected: " + connectionHandler.getClientSocket().getInetAddress());
	clients.remove(connectionHandler);
	Logger.getLogger(getClass()).info(clients.size() + "/" + maxCLients + " connected.");
    }

}
